import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class DaylightSavingPage extends StatefulWidget {
  final String initialDate;
  final List<String> initialWeeks;

  const DaylightSavingPage({
    super.key,
    this.initialDate = '2024-07-22',
    this.initialWeeks = const ['周一', '周二', '周三', '周四', '周五'],
  });

  @override
  State<DaylightSavingPage> createState() => _DaylightSavingPageState();
}

class _DaylightSavingPageState extends State<DaylightSavingPage> {
  String startTime = '07-22 14:40';
  String endTime = '07-22 14:40';

  // Date picker data
  final List<String> months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];
  final List<String> days = List.generate(
    31,
    (index) => (index + 1).toString().padLeft(2, '0'),
  );
  final List<String> hours = List.generate(
    24,
    (index) => index.toString().padLeft(2, '0'),
  );
  final List<String> minutes = List.generate(
    60,
    (index) => index.toString().padLeft(2, '0'),
  );

  int selectedMonth = 6; // Jul
  int selectedDay = 21; // 22
  int selectedHour = 14; // 14
  int selectedMinute = 40; // 40

  late String selectedDate;
  late List<String> selectedWeeks;

  @override
  void initState() {
    super.initState();
    selectedDate = widget.initialDate;
    selectedWeeks = List.from(widget.initialWeeks);
  }

  bool isSelectingStartTime = true;

  void _showDateTimePicker() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return TDDatePicker(
          title: '选择时间',
          onConfirm: (selected) {
            setState(() {
              var selected_3 =
                  '${selected['month'].toString().padLeft(2, '0')}-'
                  '${selected['day'].toString().padLeft(2, '0')}-'
                  '${selected['hour'].toString().padLeft(2, '0')}-'
                  '${selected['minute'].toString().padLeft(2, '0')}';

              // Update selectedDate with the new value
              // selectedDate = '${DateTime.now().year}-$selected_3';
              selectedDate = selected_3;

              log("rayn selectedDate: $selectedDate");
            });
            Navigator.of(context).pop();
          },
          pickerItemCount: 5,
          model: DatePickerModel(
            useYear: false,
            useMonth: true,
            useDay: true,
            useHour: true,
            useMinute: true,
            useWeekDay: false,
            useSecond: false,
            dateStart: [1999, 01, 01],
            dateEnd: [2023, 12, 31],
            dateInitial: [2012, 1, 1],
          ),
          itemBuilder:
              (
                context,
                content,
                colIndex,
                index,

                itemDistanceCalculator,
                distance,
              ) {
                if (colIndex == 1) {
                  log("ryan content: $content");
                  content = changeMonthContent(content);
                }

                return Text(
                  content,
                  style: TextStyle(
                    color: distance == 0
                        ? TDTheme.of(context).brandColor10
                        : null,
                  ),
                );
              },
        );
      },
    );
  }

  String changeMonthContent(String content) {
    switch (content) {
      case "1":
        content = "Jan";
        break;
      case "2":
        content = "Feb";
        break;
      case "3":
        content = "Mar";
        break;
      case "4":
        content = "Apr";
        break;
      case "5":
        content = "May";
        break;
      case "6":
        content = "Jun";
        break;
      case "7":
        content = "Jul";
        break;
      case "8":
        content = "Aug";
        break;
      case "9":
        content = "Sep";
        break;
      case "10":
        content = "Oct";
        break;
      case "11":
        content = "Nov";
        break;
      case "12":
        content = "Dec";
        break;
      default:
        content = "Jan";
    }
    return content;
  }

  void _showDatePicker() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('选择日期'),
          content: SizedBox(
            width: 300,
            height: 300,
            child: CalendarDatePicker(
              initialDate: DateTime.parse(selectedDate),
              firstDate: DateTime(2020),
              lastDate: DateTime(2030),
              onDateChanged: (DateTime date) {
                setState(() {
                  selectedDate = date.toString().split(' ')[0];
                });
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showWeekPicker() {
    final List<String> weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    List<String> tempSelected = List.from(selectedWeeks);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return AlertDialog(
              title: const Text('选择星期'),
              content: SizedBox(
                width: 300,
                height: 400,
                child: Column(
                  children: weekDays.map((day) {
                    return CheckboxListTile(
                      title: Text(day),
                      value: tempSelected.contains(day),
                      onChanged: (bool? value) {
                        setDialogState(() {
                          if (value == true) {
                            tempSelected.add(day);
                          } else {
                            tempSelected.remove(day);
                          }
                        });
                      },
                    );
                  }).toList(),
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    setState(() {
                      selectedWeeks = tempSelected;
                    });
                    Navigator.pop(context);
                  },
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  void _showTimePicker(bool isStart) {
    setState(() {
      isSelectingStartTime = isStart;
    });

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Container(
              height: 400,
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  // Header
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Colors.grey),
                        ),
                      ),
                      Text(
                        isStart ? '开始时间' : '结束时间',
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      TextButton(
                        onPressed: () {
                          String monthNum = (selectedMonth + 1)
                              .toString()
                              .padLeft(2, '0');
                          String newTime =
                              '$monthNum-${days[selectedDay]} ${hours[selectedHour]}:${minutes[selectedMinute]}';
                          setState(() {
                            if (isStart) {
                              startTime = newTime;
                            } else {
                              endTime = newTime;
                            }
                          });
                          Navigator.pop(context);
                        },
                        child: const Text(
                          '确定',
                          style: TextStyle(color: Colors.blue),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  // Custom Picker using ListWheelScrollView
                  Expanded(
                    child: Row(
                      children: [
                        // Month picker
                        Expanded(
                          child: ListWheelScrollView.useDelegate(
                            itemExtent: 40,
                            physics: const FixedExtentScrollPhysics(),
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                selectedMonth = index;
                              });
                            },
                            childDelegate: ListWheelChildBuilderDelegate(
                              builder: (context, index) {
                                if (index < 0 || index >= months.length) {
                                  return null;
                                }
                                return Center(
                                  child: Text(
                                    months[index],
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: index == selectedMonth
                                          ? Colors.black
                                          : Colors.grey,
                                    ),
                                  ),
                                );
                              },
                              childCount: months.length,
                            ),
                          ),
                        ),
                        // Day picker
                        Expanded(
                          child: ListWheelScrollView.useDelegate(
                            itemExtent: 40,
                            physics: const FixedExtentScrollPhysics(),
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                selectedDay = index;
                              });
                            },
                            childDelegate: ListWheelChildBuilderDelegate(
                              builder: (context, index) {
                                if (index < 0 || index >= days.length) {
                                  return null;
                                }
                                return Center(
                                  child: Text(
                                    days[index],
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: index == selectedDay
                                          ? Colors.black
                                          : Colors.grey,
                                    ),
                                  ),
                                );
                              },
                              childCount: days.length,
                            ),
                          ),
                        ),
                        // Hour picker
                        Expanded(
                          child: ListWheelScrollView.useDelegate(
                            itemExtent: 40,
                            physics: const FixedExtentScrollPhysics(),
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                selectedHour = index;
                              });
                            },
                            childDelegate: ListWheelChildBuilderDelegate(
                              builder: (context, index) {
                                if (index < 0 || index >= hours.length) {
                                  return null;
                                }
                                return Center(
                                  child: Text(
                                    hours[index],
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: index == selectedHour
                                          ? Colors.black
                                          : Colors.grey,
                                    ),
                                  ),
                                );
                              },
                              childCount: hours.length,
                            ),
                          ),
                        ),
                        // Minute picker
                        Expanded(
                          child: ListWheelScrollView.useDelegate(
                            itemExtent: 40,
                            physics: const FixedExtentScrollPhysics(),
                            onSelectedItemChanged: (index) {
                              setModalState(() {
                                selectedMinute = index;
                              });
                            },
                            childDelegate: ListWheelChildBuilderDelegate(
                              builder: (context, index) {
                                if (index < 0 || index >= minutes.length) {
                                  return null;
                                }
                                return Center(
                                  child: Text(
                                    minutes[index],
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: index == selectedMinute
                                          ? Colors.black
                                          : Colors.grey,
                                    ),
                                  ),
                                );
                              },
                              childCount: minutes.length,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        title: const Text('夏令时', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.grey[800],
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white, size: 20),
          onPressed: () {
            // Return data to the previous screen using the route model
            Navigator.pop(context, {
              'selectedDate': selectedDate,
              'selectedWeeks': selectedWeeks,
              'startTime': startTime,
              'endTime': endTime,
            });
          },
        ),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TDButton(
              text: '保存设置',
              theme: TDButtonTheme.primary,
              onTap: () {
                Navigator.pop(context, {
                  'selectedDate': selectedDate,
                  'selectedWeeks': selectedWeeks,
                  'startTime': startTime,
                  'endTime': endTime,
                });
              },
            ),
          ),
          const SizedBox(height: 20),
          // Date section
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: ListTile(
              title: const Text('日期'),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    selectedDate,
                    style: const TextStyle(color: Colors.grey),
                  ),
                  const Icon(Icons.chevron_right),
                ],
              ),
              onTap: _showDateTimePicker,
            ),
          ),
          const SizedBox(height: 20),
          // Week section
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: ListTile(
              title: const Text('周'),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    selectedWeeks.join(', '),
                    style: const TextStyle(color: Colors.grey),
                  ),
                  const Icon(Icons.chevron_right),
                ],
              ),
              onTap: _showWeekPicker,
            ),
          ),
          const SizedBox(height: 20),
          // Time section
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              children: [
                ListTile(
                  title: const Text('开始时间'),
                  trailing: Text(
                    startTime,
                    style: const TextStyle(color: Colors.grey),
                  ),
                  onTap: () => _showTimePicker(true),
                ),
                const Divider(height: 1),
                ListTile(
                  title: const Text('结束时间'),
                  trailing: Text(
                    endTime,
                    style: const TextStyle(color: Colors.grey),
                  ),
                  onTap: () => _showTimePicker(false),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
